package com.zxt.service.impl;

import com.zxt.dao.UserDao;
import com.zxt.dao.impl.UserDaoImpl;
import com.zxt.domain.User;
import com.zxt.service.UserService;
import com.zxt.util.EmailUtils;
import com.zxt.util.MD5util;

public class UserServiceImpl implements UserService {
   private UserDao userDao=new UserDaoImpl();
    @Override
    public boolean checkUsername(String username) {
        User user = userDao.selectByUsername(username);
        if (user !=null){
            return true;  //用户已存在 1
        }
        return false;  //可以注册 0
    }

    @Override
    public void regist(User user) {
        //密码加密
        user.setPassword(MD5util.md5(user.getPassword()));
        userDao.insert(user);
        //发送邮件
        EmailUtils.sendEmail(user);
    }

    @Override
    public void active(String email, String code) {
        int result=userDao.updateFlag(email,code);
    }

    @Override
    public User login(String username, String password) {
        //密码加密
        password = MD5util.md5(password);
        User user = userDao.selectByUsername(username);
        //判断用户是否存在
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        //比较密码
        if (!user.getPassword().equalsIgnoreCase(password)) {
            throw new RuntimeException("密码错误");
        }
        //激活
        if (user.getFlag() != 1) {
            throw new RuntimeException("账户未激活或已失效");
        }
        return user;
    }
}
